<template>
	<view class="myQrCode-main">
		<view class="title">常见问题</view>

		<view class="uni-textarea feedback-text-area">
			<textarea v-model="text" placeholder="可以在这里反馈您的意见哦～" />
		</view>
		<view class="upload-image">
		  <view class="uni-uploader-body">
		    <view class="u-demo-area">
		      <u-toast ref="uToast"></u-toast>
		      <view class="pre-box" v-if="!showUploadList">
		        <view class="pre-item" v-for="(item, index) in uploadedPhotoList" :key="index">
		          <image class="pre-item-image" :src="item.url" mode="aspectFill"></image>
		          <view class="u-delete-icon" @tap.stop="deleteItem(index)">
		
		            <u-icon name="close" size="20" color="#ffffff"></u-icon>
		          </view>
		          <u-line-progress v-if="item.progress > 0 && !item.error" :show-percent="false" height="16" class="u-progress"
		            :percent="item.progress"></u-line-progress>
		        </view>
		      </view>
		      <u-upload
              style="margin-left: -5px;margin-top: 10px;"
              class="u-upload" width="164" height="164" ref="uUpload" :custom-btn="customBtn"
		        :show-upload-list="showUploadList" :action="action" :auto-upload="autoUpload" :file-list="fileList"
		        :show-progress="showProgress" :deletable="deletable" :max-count="12" @on-list-change="getlist">
		        <view v-if="customBtn" slot="addBtn" class="slot-btn" hover-class="slot-btn__hover" hover-stay-time="150">
		          <u-icon name="photo" size="60" :color="$u.color['lightColor']"></u-icon>
		        </view>
		      </u-upload>
		
		    </view>
		  </view>
		</view>
		<button class="blue-wide-button" style="margin-top: 30px;" @tap="commit">
			<text class="text" >确认提交</text>
		</button>
  </view>
</template>

<script>
	import wideButton from "@/widgets/wideButton"
  import {
    TOAST_DURATION
  } from '@/util/misc'
  import {
    mapGetters,
    mapActions
  } from 'vuex'
  export default {
	  components:{
      wideButton
		},
    data() {
      return {
        text:'',
        index: 0,
        list:[],
        sourceTypeIndex: 2,
        sourceType: ['拍照', '相册', '拍照或相册'],
        sizeTypeIndex: 2,
        sizeType: ['压缩', '原图', '压缩或原图'],
        countIndex: 8,
        count: [1, 2, 3, 4, 5, 6, 7, 8, 9],
        buildlist: [],
        // uView 图片上传 data ,START
        action: 'http://www.tp5.com',
        // 预置上传列表
        fileList: [],
        // fileList: [{
        // 	url: 'http://pics.sc.chinaz.com/files/pic/pic9/201912/hpic1886.jpg',
        // 	error: false,
        // 	progress: 100
        // }],
        
        showUploadList: true,
        customBtn: false, // 个性化上传按钮?
        autoUpload: false,
        showProgress: true,
        deletable: true,
        customStyle: false,
      };
    },
	methods:{
    commit(){
      console.log('点击了按钮')
      uni.showLoading({
          title: '上传中'
      });
      let imgs = [];
      if(this.list.length>0){
        imgs = this.list.map((item,i)=>{
          return {
            name:`image[${i}]`,
            file:item.file,
            url:item.url,
            uri:item.url 
          }
        })
        console.log('imgs',imgs)
         uni.uploadFile({
              url: `${this.$http}/api/merchant/business_feedback`, //仅为示例，非真实的接口地址
              files:imgs,
              header: {
                Authorization: 'Bearer ' + this.$store.state.token
              },
              formData: {
                  content:this.text
              },
              success: (uploadFileRes) => {
                  uni.hideLoading()
                  console.log('uploadFileRes',uploadFileRes.data);
                  let res = JSON.parse(uploadFileRes.data);
                  if(res.code==200){
                    uni.showToast({
                      title: '上传成功',
                      position: 'top',
                      icon: 'none',
                      duration: TOAST_DURATION
                    });
                    this.$refs.uUpload.clear()
                    this.text ='';
                  }
              },
              fail:(fail)=>{
                console.log('fail',fail)
                uni.hideLoading()
                uni.showToast({
                  title: fail,
                  position: 'top',
                  icon: 'none',
                  duration: TOAST_DURATION
                });
              }
          });
        }else{
          console.log('noimg')
          if(this.text){
            uni.request({
              url: `${this.$http}/api/merchant/business_feedback`, 
              method:'POST',
              header: {
                Authorization: 'Bearer ' + this.$store.state.token
              },
              data: {
                  content:this.text
              },
              complete:(res)=>{
                console.log('uploadFileRes',res.data);
                if(res.data.code==200){
                  uni.showToast({
                    title: '上传成功',
                    position: 'top',
                    icon: 'none',
                    duration: TOAST_DURATION
                  });
                  this.$refs.uUpload.clear()
                  this.text ='';
                }else if(res.data.code == 402 || res.data.code == 506){
                setTimeout(()=>{
                  this.$logout(res.data.msg);
                },1500)
              }else{
                  uni.showToast({
                    title: res.data.msg,
                    position: 'top',
                    icon: 'none',
                    duration: TOAST_DURATION
                  });
                }
              }
            })
          }else{
            uni.showToast({
              title: '请输入反馈信息',
              position: 'top',
              icon: 'none',
              duration: TOAST_DURATION
            });
          }
          
        }
      
    },
    getlist(list){
      console.log('list',list)
      this.list = list;
    },
		addimag(){
			uni.chooseImage({
			    count: 9, //默认9
			    sizeType: ['original'], //可以指定是原图还是压缩图，默认二者都有
			    sourceType: ['album'], //从相册选择
			    success: (res)=> {
			        console.log('images',res.tempFilePaths);
					// uni.request({
					// 	url:`${this.$http}/api/merchant/business_feeback_image`,
					// 	method:'POST',
					// 	data:{
					// 		'image[]':res.tempFilePaths
					// 	},
					// 	success: (res) => {
					// 		console.log(res.data)
					// 	},
					// 	fail:(a)=>{
					// 		console.log(a)
					// 	}
					// })
					
					uni.uploadFile({
						url: `${this.$http}/api/merchant/business_feeback_image`,
						filePath: res.tempFilePaths[0],
						name: 'image[]',
						success: (uploadFileRes) => {
							console.log('uploadFileRes',uploadFileRes.data);
						},
						fail:(a)=>{
							console.log(a)
						}
					});
			    }
			});
		},
    chooseImage: async function() {
        // #ifdef APP-PLUS
        // TODO 选择相机或相册时 需要弹出actionsheet，目前无法获得是相机还是相册，在失败回调中处理
        if (this.sourceTypeIndex !== 2) {
          let status = await this.checkPermission();
          if (status !== 1) {
            return;
          }
        }
        // #endif
    
        if (this.imageList.length === 9) {
          let isContinue = await this.isFullImg();
          console.log("是否继续?", isContinue);
          if (!isContinue) {
            return;
          }
        }
        let _this = this;
        uni.chooseImage({
          sourceType: _this.sourceType[this.sourceTypeIndex],
          sizeType: _this.sizeType[this.sizeTypeIndex],
          count: this.imageList.length + this.count[this.countIndex] > 9 ? 9 - this.imageList.length : this.count[
            this.countIndex],
          success: (res) => {
            this.imageList = this.imageList.concat(res.tempFilePaths);
          },
          fail: (err) => {
            // #ifdef APP-PLUS
            if (err['code'] && err.code !== 0 && this.sourceTypeIndex === 2) {
              this.checkPermission(err.code);
            }
            // #endif
            // #ifdef MP
            uni.getSetting({
              success: (res) => {
                let authStatus = false;
                switch (this.sourceTypeIndex) {
                  case 0:
                    authStatus = res.authSetting['scope.camera'];
                    break;
                  case 1:
                    authStatus = res.authSetting['scope.album'];
                    break;
                  case 2:
                    authStatus = res.authSetting['scope.album'] && res.authSetting['scope.camera'];
                    break;
                  default:
                    break;
                }
                if (!authStatus) {
                  uni.showModal({
                    title: '授权失败',
                    content: 'Hello uni-app需要从您的相机或相册获取图片，请在设置界面打开相关权限',
                    success: (res) => {
                      if (res.confirm) {
                        uni.openSetting()
                      }
                    }
                  })
                }
              }
            })
            // #endif
          }
        })
      },
      isFullImg: function() {
        return new Promise((res) => {
          uni.showModal({
            content: "已经有9张图片了,是否清空现有图片？",
            success: (e) => {
              if (e.confirm) {
                this.imageList = [];
                res(true);
              } else {
                res(false)
              }
            },
            fail: () => {
              res(false)
            }
          })
        })
      },
      previewImage: function(e) {
        var current = e.target.dataset.src
        uni.previewImage({
          current: current,
          urls: this.imageList
        })
      },
      reUpload() {
        this.$refs.uUpload.reUpload();
      },
      clear() {
        this.$refs.uUpload.clear();
      },
      autoUploadChange(index) {
        this.autoUpload = index === 0;
      },
      controlChange(index) {
        if (index == 0) {
          this.showProgress = true;
          this.deletable = true;
        } else {
          this.showProgress = false;
          this.deletable = false;
        }
      },
      maxCountChange(index) {
        this.maxCount = index == 0 ? 1 : index == 1 ? 2 : 4;
      },
      customStyleChange(index) {
        if (index == 0) {
          this.showUploadList = false;
          this.customBtn = true;
    
        } else {
          this.showUploadList = true;
          this.customBtn = false;
        }
      },
      upload() {
        this.$refs.uUpload.upload();
      },
      deleteItem(index) {
        console.log(1111)
        this.$refs.uUpload.remove(index);
      },
     },
      computed:{
        ...mapGetters([]),
      }
    
  }
</script>

<style lang="scss" scoped>
	@import "../assets/styles/global";
	
	.myQrCode-main{
    padding: 15px;
    .title{
      width: 64px;
      height: 20px;
      font-family: PingFangSC-Regular;
      font-size: 16px;
      font-weight: bold;
      font-stretch: normal;
      line-height: 20px;
      letter-spacing: 0px;
      color: #06121f;
    }
		.feedback-text-area{
			margin-top: 28rpx;
			width: 686rpx;
			height: 762rpx;
			border: solid 2rpx #c8c9cc;
			padding: 28rpx;
			box-sizing: border-box;
			&::placeholder{
				width: 364rpx;
				height: 48rpx;
				font-size: 28rpx;
				line-height: 48rpx;
				color: #969799;
			}
		}
		.blue-wide-button{
      margin: 50px auto 0 auto ;
			.text{
				width: 112rpx;
				height: 32rpx;
				font-family: PingFangSC-Regular;
				font-size: 28rpx;
				font-weight: normal;
				font-stretch: normal;
				line-height: 32rpx;
				letter-spacing: 0rpx;
				color: #ffffff;
			}
		}
	}
</style>
